﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class DangNhap : System.Web.UI.Page
{
    TiemPhongDataContext db = new TiemPhongDataContext();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            HttpCookie hck = Request.Cookies["ckGhiNho"];
            if (hck != null)
            {
                txtTenDN.Text = hck["TenDN"];                
                txtMatKhau.Attributes["value"] = MD5.Decrypt(hck["MatKhau"], "ute", true);
                ckTrangThai.Checked = true;
            }
        }

    }
    protected void ibtDangKy_Click(object sender, ImageClickEventArgs e)
    {
        Response.Redirect("DangKy.aspx");
    }
    protected void ibtDangNhap_Click(object sender, ImageClickEventArgs e)
    {
        var data = db.NguoiDungs.Where(c => c.Email == txtTenDN.Text);
        if (data.Count() == 0)
        {
            lbThongBao.Text = "Tên đăng nhập không tồn tại.";
            txtTenDN.Focus();
        }
        else
        {
            NguoiDung Customers = data.ToList()[0];
            var ur = db.UserInRoles.SingleOrDefault(r => r.NguoiDungId == Customers.NguoiDungId);
            if (Customers.Password != MD5.Encrypt(txtMatKhau.Text,"ute",true))
            {
                lbThongBao.Text = "Mật khẩu không chính xác";
                txtMatKhau.Focus();
            }
            else
            {
                if (ur!=null)
                {
                    Session["DangNhap"] = Customers.NguoiDungId;
                    HttpCookie hck = new HttpCookie("ckGhiNho");
                    if (ckTrangThai.Checked)
                    {
                        hck["TenDN"] = txtTenDN.Text;
                        hck["MatKhau"] = Customers.Password;
                        hck.Expires = DateTime.Now.AddDays(30);
                    }
                    else
                        hck.Expires = DateTime.Now;
                    Response.Cookies.Add(hck);
                    if (Session["page"] != null)
                        Response.Redirect(Session["page"].ToString());
                    Response.Redirect("TrangChu.aspx");
                }
                else
                {
                    lbThongBao.Text = "Tài khoản của bạn chưa được kích hoạt, Vui lòng quay lại email đăng ký để kích hoạt tài khoản.";
                }

            }
        }
    }
}